package com.yangchoi.jetpackcompose.ui.main.viewmodel

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.yangchoi.jetpackcompose.data.pagingdatasource.HomeArticleDataSource
import com.yangchoi.lib_base.base.BaseViewModel
import com.yangchoi.lib_base.network.ApiService
import com.yangchoi.lib_base.network.entity.ArticleEntity
import com.yangchoi.lib_base.network.entity.BannerEntity
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject

@HiltViewModel
class HomeViewModel @Inject constructor(private val apiService: ApiService) : BaseViewModel() {

    var viewState by mutableStateOf(HomeViewState())

    private val articleDataList = Pager(PagingConfig(pageSize = 10)){
        HomeArticleDataSource()
    }.flow.cachedIn(viewModelScope)


    fun dispatch(event: HomeViewEvent){
        when(event){
            HomeViewEvent.OnInitHomeData -> {
                launchFlow(
                    requestBlock = {apiService.getBanner()},
                    response = {
                        if (null != it){
                            viewState = viewState.copy(
                                bannerList = it as ArrayList<BannerEntity>?
                            )
                        }
                    }
                )

                viewState = viewState.copy(pagingData = articleDataList)
            }
        }
    }

}

sealed class HomeViewEvent{
    object OnInitHomeData : HomeViewEvent()
}

data class HomeViewState(
    var bannerList: ArrayList<BannerEntity>? = null,
    var pagingData: PagingCollect? = null,
)

typealias PagingCollect = Flow<PagingData<ArticleEntity>>